﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

public partial class Sys_announcement : System.Web.UI.Page
{
    PM.PMSys.log Log = new PM.PMSys.log();
    PM.PMSys.attached Att = new PM.PMSys.attached();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["depart"] == null || Session["usertype"] == null || Session["usertype"]==null)
            Response.Redirect("../Error/Error.htm");
        if (!IsPostBack)
        {
            ddlbind();
            //学院管理员只能看自己学院的
            if (Session["usertype"].ToString() == "2")
            {
                this.ddlCollege.SelectedValue = Session["depart"].ToString();
                this.ddlCollege.Enabled = false;
            }
        }
    }

    protected void ddlbind()
    {
        string sql1 = "select id,btnname from Sys_Guide where btnstate<>'admin'";
        string sql2 = "select collegename from Dict_College";
        PM.Code.Web.controlbind.BindDropDownList(this.ddlType, this.ddlCollege, sql1, sql2, "btnname", "id", "collegename", "collegename");
        this.ddlType.Items.Insert(0,new ListItem("所有","0"));
        this.ddlCollege.Items.Insert(0, new ListItem("所有", "0"));
    }
    //导出文件
    protected void btnFileOut_Click(object sender, EventArgs e)
    {
        //检查合法性
        if (this.txtExcelName.Text.Trim() == string.Empty)
        {
            PM.Code.Web.alertmessage.ShowMsg("表格名称不能为空！");
            return;
        }
        if (this.txtYear.Text.Trim() != string.Empty)
        {
            if (!Regex.IsMatch(this.txtYear.Text.Trim(), "^[1-9][0-9]*$"))
            {
                PM.Code.Web.alertmessage.ShowMsg("年份输入非法！");
                return;
            }
        }
        //检查字段选择
        int i = 0;
        foreach (ListItem li in cblFields.Items)
        {
            if (li.Selected == true)
                i++;
        }
        if(i==0)
        {
             PM.Code.Web.alertmessage.ShowMsg("不允许所有字段都为空！");
             return;
        }
        StringBuilder sqlstr = new StringBuilder("select ");
        getsql(ref sqlstr);
        DataTable mytable = PM.Code.DAL.DbHelper.ExecuteDataTableBySql(sqlstr.ToString());
        PM.Code.Web.output.DataTableToExcel(mytable, this.txtExcelName.Text.Trim());
    }


    protected void getsql(ref StringBuilder sqlstr)
    {
        //生成field
        int i=1;
        foreach (ListItem li in cblFields.Items)
        {
            if (li.Selected == true)
            {
                if (i == 1)
                    sqlstr.Append(li.Value).Append(" as ").Append(li.Text);
                else
                {
                    if (li.Value.Trim() == "status")
                    {
                        sqlstr.Append(", case ").Append(li.Value).Append(" when 0 then '保存' when 1 then '待初审' when 2 then '待终审' when 3 then '待中期检查' ");
                        sqlstr.Append("when 4 then '待结题' when 5 then  '已结题'  when 10 then '取消' when 11 then '延期' when 20 then '初审退回' when 21 then '终审退回' else '其他' end as 状态");
                    }
                    else
                        sqlstr.Append(", ").Append(li.Value).Append(" as ").Append(li.Text);
                }
                i++;
            }
        }
        sqlstr.Append(" from View_Projects where pnature=1 ");
        //生成where
        if (this.ddlType.SelectedValue != "0")
            sqlstr.Append("and ptypeid='").Append(this.ddlType.SelectedValue.Trim()).Append("' ");
        if (this.ddlPLevel.SelectedValue != "0")
            sqlstr.Append("and plevel='").Append(this.ddlPLevel.SelectedValue.Trim()).Append("' ");
        if(this.ddlPType.SelectedValue!="0")
            sqlstr.Append("and ptype='").Append(this.ddlPType.SelectedValue.Trim()).Append("' ");
        if (this.ddlCollege.SelectedValue != "0")
            sqlstr.Append("and pcollege='").Append(this.ddlCollege.SelectedValue.Trim()).Append("' ");
        if (this.ddlPWay.SelectedValue != "0")
            sqlstr.Append("and pway='").Append(this.ddlPWay.SelectedValue.Trim()).Append("' ");
        if (this.ddlPstatus.SelectedValue != "all")
            sqlstr.Append("and status=").Append(this.ddlPstatus.SelectedValue.Trim()).Append(" ");
        if (this.txtPlanCode.Text.Trim() != string.Empty)
            sqlstr.Append("and pcode='").Append(this.txtPlanCode.Text.Trim()).Append("' ");
        if (this.txtYear.Text.Trim() != string.Empty)
        {
            sqlstr.Append(" and year(builddate) =").Append(this.txtYear.Text.Trim()).Append(" ");
            this.txtOpen.Value = "";
            this.txtOpen.Value = "";
        }
        if (this.txtOpen.Value.Trim() != string.Empty)
            sqlstr.Append("and builddate>='").Append(this.txtOpen.Value.Trim()).Append("' ");
        if (this.txtClose.Value.Trim() != string.Empty)
            sqlstr.Append("and builddate<='").Append(this.txtClose.Value.Trim()).Append("' ");
    }
    //上传文件
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        string filepath = "";
        //构建名字
        string no = createFileName();
        filepath = UpLoadFile(no);
        if (filepath == "1")//大小限制
        {
            PM.Code.Web.alertmessage.ShowMsg("抱歉！文档的大小不能超过4M，请重新上传");
            return;
        }
        else if (filepath == "2")//不是word文档
        {
            PM.Code.Web.alertmessage.ShowMsg("抱歉！只支持上传zip,rar,7zip,doc,docx,xls,xlsx,pdf格式的文档，请重新上传");
            return;
        }
        else if (filepath == "3")//文件名为空
        {
            PM.Code.Web.alertmessage.ShowMsg("您的文件名为空！请重新上传");
            return;
        }
        else if (filepath == "4")//文件名过长
        {
            PM.Code.Web.alertmessage.ShowMsg("您的文件名过长（超过50个汉字）！请重新上传");
            return;
        }
        else if(this.txtFileName.Text.Trim()==string.Empty)
        {
            PM.Code.Web.alertmessage.ShowMsg("文件名称不能为空！");
            return;
        }
        else
        {
            //添加数据库中以及操作日志
            Att.Insert_Attach(this.txtFileName.Text.Trim(), filepath, this.ddlFileType.SelectedValue);
            Log.Insert_Log("上传了一个系统附件",6);
            PM.Code.Web.alertmessage.ShowMsg("您的文件上传成功！");
            this.txtFileName.Text = "";
        }
    }
    protected string createFileName()
    {
        StringBuilder filename = new StringBuilder();
        string submitdate = DateTime.Now.ToString("yyyy-MM-dd");
        string flag = DateTime.Now.Millisecond.ToString();
        filename.Append(submitdate).Append("-").Append(flag);
        return filename.ToString();
    }
    /// <summary>
    /// 上传附件（限doc格式）
    /// </summary>
    /// <param name="NO">唯一编号</param>
    /// <returns>返回文件相对路径</returns>
    protected string UpLoadFile(string NO)
    {
        try
        {
            if (!string.IsNullOrEmpty(this.FileUpload1.PostedFile.FileName))
            {
                string checkresult = CheckFile(FileUpload1);
                if (checkresult == "9")
                {
                    string name = this.FileUpload1.FileName;
                    if (name != string.Empty)
                    {
                        string path = Server.MapPath("../ckfinder/userfiles/files" + "//"+"系统附件");//绝对路径
                        if (!System.IO.Directory.Exists(path))
                        {
                            //创建制定文件夹
                            System.IO.Directory.CreateDirectory(path);
                        }
                        string AllFileName = FileUpload1.PostedFile.FileName;
                        string LastFileName = AllFileName.Substring(AllFileName.LastIndexOf(".") + 1).ToLower();
                        string path1 = "../ckfinder/userfiles/files" + "/系统附件";//相对路径
                        name = name.Replace("."+LastFileName, "");
                        if (name.Length > 100)
                            return "4";//文件名过长
                        else
                        {
                            path += "/" + name + NO + "."+LastFileName;
                            path1 += "/" + name + NO + "." + LastFileName;
                            FileUpload1.SaveAs(path);//绝对路径
                            return path1;//数据库中存相对路径
                        }
                    }
                }
                else
                    return checkresult;
            }
            return "3";//文件没有或者名字为空
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// 验证文件类型
    /// </summary>
    /// <param name="fileName">上传控件</param>
    /// <returns>返回错误</returns>
    public string CheckFile(FileUpload fileName)
    {
        string AllFileName = fileName.PostedFile.FileName;
        string LastFileName = AllFileName.Substring(AllFileName.LastIndexOf(".") + 1).ToLower();
        if (LastFileName == "zip"||LastFileName=="rar"||LastFileName=="7zip"||LastFileName=="doc"||LastFileName=="docx"||
            LastFileName == "xls" || LastFileName == "xlsx" || LastFileName == "pdf")
        {
            if (FileUpload1.PostedFile.ContentLength / 1024 / 1024 >= 4)
                return "1";//返回错误1：大小超标
            else
                return "9";//检验合格
        }
        else
            return "2";//返回错误2：不是允许的文档
    }
}
